package com.niudong.esdemo.LZ4IO;

import org.apache.lucene.codecs.compressing.CompressionMode;
import org.apache.lucene.codecs.compressing.Compressor;
import org.apache.lucene.codecs.compressing.Decompressor;
import org.apache.lucene.store.ByteArrayDataInput;
import org.apache.lucene.store.ByteArrayDataOutput;
import org.apache.lucene.util.BytesRef;
import org.junit.Test;

import java.io.*;


public class Demo05 {

    @Test
    public void compress()throws Exception{
        BufferedReader br = new BufferedReader(new FileReader("demo05/data/2.txt"));
        FileOutputStream fos = new FileOutputStream("demo05/data/3.txt");
        Compressor compressor = CompressionMode.HIGH_COMPRESSION.newCompressor();
        byte[] outPutBytes = new byte[8196];
        ByteArrayDataOutput dataOutput = new ByteArrayDataOutput(outPutBytes);
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println("字符串byte长度：" +line.getBytes().length);
            byte[] bytes = line.getBytes();
            compressor.compress(bytes,0,bytes.length,dataOutput);
            fos.write(outPutBytes,0,dataOutput.getPosition());
            System.out.println("压缩后：" + dataOutput.getPosition());
            fos.write("\r\n".getBytes());
            dataOutput.reset(outPutBytes);
        }
       // LZ4Factory.fastestInstance().
        //6. 释放资源.
        fos.close();
        br.close();
    }

    @Test
    public void decompress()throws Exception{
        BufferedReader br = new BufferedReader(new FileReader("demo05/data/3.txt"));
        BufferedWriter bw   =new BufferedWriter(new FileWriter("demo05/data/4.txt"));
        Decompressor decompressor = CompressionMode.HIGH_COMPRESSION.newDecompressor();
        byte[] outPutBytes = new byte[8196];
        ByteArrayDataInput dataInput = new ByteArrayDataInput(outPutBytes);
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println("字符：" +line.getBytes());
            System.out.println("字符串byte长度：" +line.getBytes().length);
            byte[] bytes = line.getBytes();

            BytesRef ref = new BytesRef(8196);
            decompressor.decompress(dataInput,bytes.length,0,bytes.length,ref);
            System.out.println("解压字符串后：：" + ref.utf8ToString().length());

            bw.write(ref.utf8ToString());

            bw.newLine();
        }
        //6. 释放资源.
        bw.close();
        br.close();
    }

}
